package db

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"ir/core"
	"ir/models/structs"
	"ir/utils"
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"
	"xorm.io/xorm"
)

var Engine *xorm.Engine

type DB struct {
	*xorm.Session
}

func decodeDsn(cipherText, key string) string {
	return utils.AesDecrypt(cipherText, key)
}

func Conn() *DB {
	return &DB{
		Session: Engine.NewSession(),
	}
}

func (d *DB) Row(query structs.Query) (exist bool) {
	session := d.Session
	if query.Where != nil {
		session.Where(query.Where, query.Binds...)
	}
	if len(query.Cols) > 0 {
		session.Cols(query.Cols...)
	}
	if query.Result == nil {
		log.Println("require Result field in the query struct")
	} else {
		var err error
		exist, err = session.Get(query.Result)
		if err != nil {
			log.Println(err)
		}
	}
	return
}

func (d *DB) Rows(query structs.Query) {
	session := d.Session
	if len(query.Cols) > 0 {
		session.Cols(query.Cols...)
	}
	if query.Where != nil {
		session.Where(query.Where, query.Binds...)
	}
	if query.OrderBy != "" {
		session.OrderBy(query.OrderBy)
	}
	if query.Result == nil {
		log.Println("require Result field in the query struct")
	} else {
		err := session.Limit(query.Size, query.Offset).Find(query.Result)
		if err != nil {
			log.Println(err)
		}
	}
	return
}

func DataIsDuplicate(err error) (is bool) {
	if err == nil {
		return
	}
	str := err.Error()
	is = strings.Contains(str, "Error 1062")
	return
}

func ValueAddMarker(str, mark string) (res string) {
	str = ValueRemoveMarker(str)
	res = fmt.Sprintf("%s-{%s}", str, mark)
	return
}

func ValueRemoveMarker(str string) (res string) {
	c := regexp.MustCompile(`-\{[^\}]+\}`)
	res = c.ReplaceAllString(str, "")
	return
}

func ValueAddTsMarker(str string, ts int64) (res string) {
	sTs := strconv.FormatInt(ts, 10)
	res = ValueAddMarker(str, sTs)
	return
}

func DatabaseConnectionPool() {
	//dsn := "root:123456@tcp(localhost:3306)/exengine?charset=utf8"
	//dsn := "dev:123456@tcp(xxxg.xxx.xxx.xxx:3306)/zj?charset=utf8"
	config := core.GetConfig()
	enDsn := config.GetString("db.main")
	key := config.GetString("key")
	dsn := decodeDsn(enDsn, key)

	var re = regexp.MustCompile(`tcp\((.*)\)`)
	matches := re.FindStringSubmatch(dsn)
	if len(matches) == 2 {
		log.Println("mysql host is", matches[1], dsn)
	}

	engine, err := xorm.NewEngine("mysql", dsn)
	if err != nil {
		log.Println("退出程序,检查配置是否正确")
		panic(err.Error())
	}
	err = engine.Ping()
	if err != nil {
		log.Println("连接mysql连接池创建失败,马上检查mysql配置是否正确,程序已经终止运行....")
		os.Exit(1)
	}
	engine.ShowSQL(true)
	Engine = engine
}
